<template>
  <!-- 检验系统 引用顶部菜单  左侧菜单全局LayoutV1 -->
  <div id="homepage">
    <el-container class="homecontainer">
      <el-header class="homeheader">
        <HomePageToolbar :moduleList="moduleList" :moduleName="moduleName" @getModuleSystemFunction="getModuleSystemFunction"></HomePageToolbar>
      </el-header>
      <Splitpanes class="area">
        <Pane :size="15">
          <el-scrollbar>
            <el-tree ref="leftTree" :data="interfaceSystemList" default-expand-all :props="defaultProps" v-loading="treeLoading" @node-click="handleNodeClick" node-key="commonId" highlight-current :current-node-key="currentTreeId" />
          </el-scrollbar>
        </Pane>
        <Pane :size="85">
          <vxe-toolbar perfect>
            <template #tools>
              <!-- <vxe-button type="text" class="button-blue" icon="vxe-icon-square-fill" content="自动审核"></vxe-button> -->
              <vxe-button class="button-blue" icon="vxe-icon-setting-fill" @click="wkltConfig"></vxe-button>
            </template>
          </vxe-toolbar>
          <el-scrollbar style="height: 100%">
            <div class="flex flex-wrap padding-sm">
              <el-card class="margin-lr-sm margin-tb-sm cursor" style="text-align: center;" :class="m.actived ? 'bg-blue light' : ''" v-for="(m, i) in cards" :key="i" @click="cardChange(m)">
                <img :src="`${getAssetsFile('images/interfacePlatform/' + m.picture)}`" alt class="homeimg" />
                <div class="text item" style="width:150px">{{ m.name }}</div>
              </el-card>
            </div>
          </el-scrollbar>
          <el-dialog title="功能模块" :show-close="false" v-model="showInterfaceFunctionDialog" append-to-body :close-on-click-modal="false" width="800px">
            <div class="setFieldsDialog">
              <vxe-table ref="tableColumnRef" class="mytable-scrollbar" border align="center" max-height="490px" :data="interfaceFunctionList" :row-config="{ isCurrent: true, isHover: true, useKey: true, keyField: 'commonId' }" :column-config="{ resizable: true }" :checkbox-config="{
                checkMethod: checCheckboxkMethod2,
                checkRowKeys: defaultSelecteRowKeys
              }" resizable show-overflow keep-source>
                <vxe-column type="checkbox" width="50px" align="center"></vxe-column>
                <vxe-column field="code" title="字段名" width="150"> </vxe-column>
                <vxe-column field="name" title="字段描述"> </vxe-column>
                <vxe-column field="inputCode" title="字段类型" width="150"> </vxe-column>
                <vxe-column field="columnId" title="字段顺序" width="150"> </vxe-column>
              </vxe-table>

              <div class="setFieldsFooter flex right justify-end" style="margin-top: 10px">
                <el-button type="primary" @click="saveBatchInterfaceFunction()">保存</el-button>
                <el-button @click="closeInterfaceFunctionDialog()">取消</el-button>
              </div>
            </div>
          </el-dialog>
        </Pane>
      </Splitpanes>
    </el-container>

    <vxe-modal class-name="animation-slide-right" modal-class="drawerBulkModal" v-model="moduleDialog1" :title="headTitle" width="100vw" height="100vh" show-zoom resize>
      <template #default>
        <InterfaceDict v-if="pathUrl === 1" :systemId="interfaceForm.systemId" :moduleId="interfaceForm.moduleId" :moduleSystemName="moduleSystemName" />
        <InterfaceSet v-else-if="pathUrl === 2" :systemId="interfaceForm.systemId" :moduleId="interfaceForm.moduleId" :moduleSystemName="moduleSystemName" />
        <Job v-else-if="pathUrl === 3" :systemId="interfaceForm.systemId" :moduleId="interfaceForm.moduleId" :moduleSystemName="moduleSystemName"></Job>
        <InterfaceSceneSet v-else-if="pathUrl === 4" :systemId="interfaceForm.systemId" :moduleId="interfaceForm.moduleId" :moduleSystemName="moduleSystemName"></InterfaceSceneSet>
        <LogTack v-else-if="pathUrl === 5" :systemId="interfaceForm.systemId" :moduleId="interfaceForm.moduleId" :moduleSystemName="moduleSystemName"></LogTack>
        <LabUploadItemVsItem v-else-if="pathUrl === 6" :systemId="interfaceForm.systemId" :moduleId="interfaceForm.moduleId" :moduleSystemName="moduleSystemName"></LabUploadItemVsItem>
        <InterfaceCAUser v-else-if="pathUrl === 7" :systemId="interfaceForm.systemId" :moduleId="interfaceForm.moduleId" :moduleSystemName="moduleSystemName"></InterfaceCAUser>
        <InterfaceAuditInfo v-else-if="pathUrl === 8" :systemId="interfaceForm.systemId" :moduleId="interfaceForm.moduleId" :moduleSystemName="moduleSystemName"></InterfaceAuditInfo>
      </template>
    </vxe-modal>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, getCurrentInstance } from 'vue';
import { AppStore } from '@/stores/store';
import HomePageToolbar from '@/components/HomePageToolbar.vue';
import { Splitpanes, Pane } from 'splitpanes';
import { notifyType, notifyMessage, getAssetsFile } from '@/utils/common';
import InterfaceDict from '@/views/interface/InterfaceDict.vue';
import InterfaceSet from '@/views/interface/InterfaceSet.vue';
import InterfaceSceneSet from '@/views/interface/InterfaceSceneSet.vue';
import LogTack from './LogTack.vue';
import LabUploadItemVsItem from './LabUploadItemVsItem.vue';
import Job from '@/views/interface/Job.vue';
import InterfaceCAUser from '@/views/interface/InterfaceCAUser.vue';
import InterfaceAuditInfo from '@/views/interface/InterfaceAuditInfo.vue';

let store = AppStore();
let conWidth = ref(document.documentElement.clientWidth); //获取屏幕宽度

let { proxy }: any = getCurrentInstance();
let menuToolList: any = reactive([]);
let showInterfaceFunctionDialog = ref(false); //中间设计模式 设置字段弹框
let moduleSystemName = ref('');
let moduleName = ref('');
let headTitle = ref('');

// t图表数据
onMounted(() => {
  console.log('-----------》》》走这个');
  getDictDetailList(); /**获取接口系统类型字典 */
  // getCardsList();
});
let pathUrl = ref(0); /**页面路由 */
let moduleDialog1 = ref(false); /**系统切换弹窗 */
let moduleDialog2 = ref(false); /**系统切换弹窗 */
let interfaceFunctionList = reactive([]);

/**功能卡片 */
let cards = reactive([]);

// 菜单数据
let menuList = reactive([]);
const defaultProps = reactive({
  children: 'children',
  label: 'name'
});

let interfaceForm = ref({});

let interfaceSystemList = reactive([]);
let interfaceSystemChildrenList = reactive([]);
let moduleList = reactive([]);

let defaultSelecteRowKeys = reactive([]);
// 弹框 表格复选框(是否允许用户手动勾选)
function checCheckboxkMethod2({ row }: any) {
  defaultSelecteRowKeys.length = 0;
  const obj = cards.filter((p: any) => {
    defaultSelecteRowKeys.push(p.commonId);
    //return p.commonId == row.commonId;
  });
  return obj.length == 0;
}

// 获取申请项目列表
function getCardsList() {
  cards.length = 0;
  const url = '/api/sys/SysInterfaceFunction/findSysInterfaceFunctionTree';
  let obj = {
    moduleId: interfaceForm.value.moduleId,
    systemId: interfaceForm.value.systemId
  };
  proxy.$http
    .get(url, { params: obj })
    .then((res: any) => {
      cards.length = 0;
      cards.push(...res.data);
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}

//获取字典数据
async function getDictDetailList() {
  interfaceSystemList.length = 0;
  interfaceFunctionList.length = 0;
  interfaceSystemChildrenList.length = 0;
  const codes = 'InterfaceSystem,InterfaceFunction';
  const url = '/api/sys/basDictDetail/findDictDetailListByDictCodes';
  const dictTreeTypeItems: any = await proxy.$http.get(url, { params: { code: codes } });
  let itemClassType = dictTreeTypeItems.data.find((item) => item.code === 'InterfaceSystem');
  interfaceSystemChildrenList.push(...itemClassType.detailDataList);
  // setCurTypeNode(itemClassType.detailDataList[0].commonId);
  const instrClassType = dictTreeTypeItems.data.find((item) => item.code === 'InterfaceFunction');
  interfaceFunctionList.push(...instrClassType.detailDataList);

  await finPermissionObj();
}

//获取选中系统得树形结构的信息
async function getModuleSystemFunction(item) {
  interfaceForm.value.moduleId = item.id;
  interfaceSystemList.length = 0;
  const url = '/api/sys/basDictDetail/findDictDetailList';
  await proxy.$http
    .get(url, { params: { code: 'InterfaceModule' } })
    .then((res: any) => {
      const data = {
        name: item.name,
        code: '01',
        children: []
      };
      const filterData = res.data.filter((p) => p.moduleId == item.name).map((s) => s.interfaceSystem);
      //需要获取
      let datas = [];
      datas = interfaceSystemChildrenList.filter((p) => filterData.indexOf(p.code) > -1);
      data.children.push(...datas);
      interfaceSystemList.push(data);
      if (data.children[0]) {
        setCurTypeNode(data.children[0]);
      }
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}

function finPermissionObj() {
  moduleList.length = 0;
  proxy.$http
    .get('/api/sys/SysInterfaceFunction/findSysInterfaceModule')
    .then((res: any) => {
      if (res.status.code !== 1) {
        notifyMessage(res.status.msg, notifyType.warning, proxy);
        return;
      }
      moduleList.push(...res.data);
      if (moduleList.length > 0) {
        moduleName.value = moduleList[0].name;
        getModuleSystemFunction(moduleList[0]);
      }
    })
    .catch((err: string) => {
      notifyMessage(err, notifyType.warning, proxy);
    });
}

// 光标定位在指定字典分类上
function setCurTypeNode(item) {
  proxy.$nextTick(() => {
    const treeName = 'leftTree';
    const tree: any = proxy.$refs[treeName];
    tree.setCurrentKey(item.commonId);
  });
  interfaceForm.value.systemId = item.commonId;
  moduleSystemName.value = interfaceSystemList[0].name + '-' + item.name;
  getCardsList();
}

function wkltConfig() {
  showInterfaceFunctionDialog.value = true;
  //选中的id有
  proxy.$nextTick(() => {
    const $table = proxy.$refs.tableColumnRef;
    if ($table) {
      $table.setCheckboxRow(cards, true);
    }
  });
}

function closeInterfaceFunctionDialog() {
  // 清除所有行选中
  const $table = proxy.$refs.tableColumnRef;
  if ($table) {
    $table.clearCheckboxRow();
  }
  showInterfaceFunctionDialog.value = false;
}

function handleNodeClick(node) {
  moduleSystemName.value = interfaceSystemList[0].name + '-' + node.name;
  interfaceForm.value.systemId = node.commonId;
  getCardsList();
}

function saveBatchInterfaceFunction() {
  const selectRows = (proxy.$refs.tableColumnRef as any).getCheckboxRecords();
  const datas = [];
  selectRows.forEach((element) => {
    const data = {
      moduleId: interfaceForm.value.moduleId,
      systemId: interfaceForm.value.systemId,
      functionId: element.commonId
    };
    datas.push(data);
  });
  let url = '/api/sys/SysInterfaceFunction/addSysInterfaceFunction';
  proxy.$http
    .post(url, datas)
    .then((res: any) => {
      showInterfaceFunctionDialog.value = false;
      const data = {
        id: interfaceForm.value.moduleId,
        name: interfaceSystemList[0].name
      };
      getModuleSystemFunction(data);
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}

/**功能卡片点击 */
function cardChange(item) {
  console.log(item);
  headTitle.value = item.name;
  if (item.url == '/interfaceDict') {
    pathUrl.value = 1;
  } else if (item.url == '/interfaceset') {
    pathUrl.value = 2;
  } else if (item.url == '/job') {
    pathUrl.value = 3;
  } else if (item.url == '/interfaceSet') {
    pathUrl.value = 4;
  } else if (item.url == '/log') {
    pathUrl.value = 5;
  } else if (item.url == '/uploadItemVsItem') {
    pathUrl.value = 6;
  } else if (item.url == '/userInfo') {
    pathUrl.value = 7;
  } else if (item.url == '/bbshjl') {
    pathUrl.value = 8;
  }
  cards.forEach((p) => {
    p.actived = false;
  });
  item.actived = true;
  moduleDialog1.value = true;
}
</script>
<style lang="scss" scoped>
#homepage {
  width: calc(100%);
  height: calc(100%);
  background-color: $bg-white;

  .el-container {
    height: 100%;

    .el-header {
      padding: 0 !important;
      height: 50px;
    }

    .el-main {
      padding: 0;
      width: 100%;
      height: calc(100% - 50px);
    }
  }

  .homeimg {
    width: 70px;
    height: 70px;
  }

  .drawerBulkModal {
    z-index: 1000;
    inset: 50px 0 0 70px !important;
  }
}
</style>
